package com.thirdgroup.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/uploadProfilePicture")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2 MB
        maxFileSize = 1024 * 1024 * 10,      // 10 MB
        maxRequestSize = 1024 * 1024 * 50)   // 50 MB
public class UploadProfilePictureServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uniqueFileName = null;
        String saveDir = getServletContext().getRealPath("/") + "uploads"; // Save directory in webapp/uploads
        File uploadDir = new File(saveDir);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        try {
            Part filePart = request.getPart("file"); // 获取上传的文件部分
            String fileName = getSubmittedFileName(filePart); // 获取文件名
            if (fileName != null && !fileName.isEmpty()) {
                uniqueFileName = generateUniqueFileName(fileName); // 生成唯一文件名
                System.out.println("uniqueFileName---->"+uniqueFileName);
                saveImageFromPart(filePart, uniqueFileName, saveDir); // 保存图片文件
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("上传失败");
            return;
        }
        if (uniqueFileName != null) {
            response.getWriter().write(uniqueFileName); // 返回唯一文件名
        } else {
            response.getWriter().write("上传失败");
        }
    }

    // 生成唯一的文件名
    private String generateUniqueFileName(String fileName) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timestamp = sdf.format(new Date());
        String extension = fileName.substring(fileName.lastIndexOf("."));
        return timestamp + extension;
    }

    // 从Part中保存图片文件
    private void saveImageFromPart(Part filePart, String fileName, String saveDir) {
        try (InputStream fileContent = filePart.getInputStream()) {
            Files.copy(fileContent, Paths.get(saveDir, fileName), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 获取文件名（兼容不同浏览器）
    private String getSubmittedFileName(Part part) {
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }
}
